<template>
  <view class="checkin-container">
    <view class="header">
      <text class="title">签到管理</text>
      <text class="subtitle">课程签到统计与管理</text>
    </view>

    <view class="tab-bar">
      <view 
        v-for="tab in tabs" 
        :key="tab.value"
        :class="['tab-item', { active: activeTab === tab.value }]"
        @click="activeTab = tab.value"
      >
        {{ tab.label }}
      </view>
    </view>
    
    <!-- 发起签到 -->
    <view v-if="activeTab === 'create'" class="tab-content">
      <view class="create-section">
        <view class="form-item">
          <text class="label">选择课程</text>
          <picker @change="onCourseChange" :value="courseIndex" :range="courses" range-key="courseName">
            <view class="picker-value">{{ courses[courseIndex]?.courseName || '请选择课程' }}</view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="label">签到有效时间</text>
          <picker :value="durationIndex" :range="durations" @change="onDurationChange">
            <view class="picker-value">{{ durations[durationIndex] }}</view>
          </picker>
        </view>
        
        <view class="qr-section" v-if="currentSession">
          <text class="section-title">签到二维码</text>
          <view class="qr-code-container">
            <canvas canvas-id="qrcodeCanvas" class="qrcode-canvas"></canvas>
          </view>
          <text class="session-code">签到码: {{ currentSession.sessionId }}</text>
          <text class="expire-time">有效期至: {{ currentSession.expireTime }}</text>
          
          <view class="action-buttons">
            <button class="btn secondary" @click="copySessionCode">复制签到码</button>
            <button class="btn primary" @click="shareCheckin">分享签到</button>
          </view>
        </view>
        
        <button class="create-btn" @click="createCheckinSession" :disabled="!selectedCourse">
          {{ currentSession ? '重新生成' : '发起签到' }}
        </button>
      </view>
    </view>
    
    <!-- 签到统计 -->
    <view v-else-if="activeTab === 'stats'" class="tab-content">
      <view class="stats-section">
        <view class="stats-cards">
          <view class="stat-card">
            <text class="stat-value">{{ todayStats.total }}</text>
            <text class="stat-label">今日签到</text>
          </view>
          <view class="stat-card">
            <text class="stat-value">{{ todayStats.present }}</text>
            <text class="stat-label">已签到</text>
          </view>
          <view class="stat-card">
            <text class="stat-value">{{ todayStats.absent }}</text>
            <text class="stat-label">未签到</text>
          </view>
          <view class="stat-card">
            <text class="stat-value">{{ todayStats.rate }}%</text>
            <text class="stat-label">签到率</text>
          </view>
        </view>
        
        <view class="checkin-list">
          <view class="section-title">今日签到记录</view>
          <view v-if="todayRecords.length === 0" class="empty-state">
            <text>今日暂无签到记录</text>
          </view>
          <view v-else class="records">
            <view v-for="record in todayRecords" :key="record.id" class="record-item">
              <view class="record-info">
                <text class="course-name">{{ record.courseName }}</text>
                <text class="checkin-time">{{ record.startTime }} - {{ record.endTime }}</text>
                <text class="student-count">{{ record.presentCount }}/{{ record.totalCount }}人</text>
              </view>
              <text class="checkin-rate">{{ record.rate }}%</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 历史记录 -->
    <view v-else-if="activeTab === 'history'" class="tab-content">
      <view class="history-section">
        <view class="date-filter">
          <text class="filter-label">选择日期</text>
          <picker mode="date" :value="filterDate" @change="onDateChange">
            <view class="picker-value">{{ filterDate }}</view>
          </picker>
        </view>
        
        <view class="history-list">
          <view v-if="historyRecords.length === 0" class="empty-state">
            <text>暂无历史记录</text>
          </view>
          <view v-else class="records">
            <view v-for="record in historyRecords" :key="record.id" class="record-item detailed">
              <view class="record-header">
                <text class="course-name">{{ record.courseName }}</text>
                <text class="record-date">{{ record.date }}</text>
              </view>
              <view class="record-details">
                <text class="detail-item">时间: {{ record.timeRange }}</text>
                <text class="detail-item">应到: {{ record.totalCount }}人</text>
                <text class="detail-item">实到: {{ record.presentCount }}人</text>
                <text class="detail-item">签到率: {{ record.rate }}%</text>
              </view>
              <view class="record-actions">
                <button class="btn small" @click="viewDetail(record)">查看详情</button>
                <button class="btn small secondary" @click="exportRecord(record)">导出</button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { api } from '@/utils/request.js'

export default {
  data() {
    const today = new Date().toISOString().split('T')[0]
    return {
      activeTab: 'create',
      tabs: [
        { label: '发起签到', value: 'create' },
        { label: '签到统计', value: 'stats' },
        { label: '历史记录', value: 'history' }
      ],
      courseIndex: 0,
      courses: [],
      durationIndex: 2,
      durations: ['5分钟', '10分钟', '15分钟', '20分钟', '30分钟'],
      currentSession: null,
      filterDate: today,
      todayStats: {
        total: 0,
        present: 0,
        absent: 0,
        rate: 0
      },
      todayRecords: [],
      historyRecords: []
    }
  },

  onLoad() {
    this.loadCourses()
    this.loadTodayStats()
    this.loadHistoryRecords()
  },

  methods: {
    async loadCourses() {
      try {
        // 模拟教师课程数据
        this.courses = [
          { courseId: 'C001', courseName: 'Web前端开发', className: '计算机1班' },
          { courseId: 'C002', courseName: '数据库原理', className: '计算机2班' },
          { courseId: 'C003', courseName: '软件工程', className: '软件工程1班' }
        ]
      } catch (error) {
        console.error('加载课程失败:', error)
      }
    },
    
    async createCheckinSession() {
      if (!this.courses[this.courseIndex]) {
        uni.showToast({ title: '请选择课程', icon: 'none' })
        return
      }
      
      try {
        const selectedCourse = this.courses[this.courseIndex]
        const duration = parseInt(this.durations[this.durationIndex])
        
        const res = await api.createCheckinSession({
          courseId: selectedCourse.courseId,
          duration: duration
        })
        
        if (res.code === 200) {
          this.currentSession = {
            sessionId: res.data.sessionId,
            expireTime: res.data.expireTime,
            qrcodeUrl: res.data.qrcodeUrl
          }
          
          uni.showToast({ title: '签到已创建', icon: 'success' })
          this.generateQRCode(res.data.sessionId)
        }
      } catch (error) {
        uni.showToast({ title: '创建签到失败', icon: 'none' })
      }
    },
    
    generateQRCode(sessionId) {
      // 这里应该使用二维码生成库
      // 暂时用文本代替
      console.log('生成二维码:', sessionId)
    },
    
    copySessionCode() {
      if (!this.currentSession) return
      
      uni.setClipboardData({
        data: this.currentSession.sessionId,
        success: () => {
          uni.showToast({ title: '签到码已复制', icon: 'success' })
        }
      })
    },
    
    shareCheckin() {
      if (!this.currentSession) return
      
      uni.share({
        title: '课堂签到',
        content: `请扫描二维码或输入签到码：${this.currentSession.sessionId}`,
        href: this.currentSession.qrcodeUrl,
        success: () => {
          uni.showToast({ title: '分享成功', icon: 'success' })
        }
      })
    },
    
    async loadTodayStats() {
      try {
        // 模拟今日统计数据
        this.todayStats = {
          total: 156,
          present: 142,
          absent: 14,
          rate: 91
        }
        
        this.todayRecords = [
          {
            id: 1,
            courseName: 'Web前端开发',
            startTime: '08:00',
            endTime: '09:40',
            presentCount: 45,
            totalCount: 45,
            rate: 100
          },
          {
            id: 2,
            courseName: '数据库原理',
            startTime: '10:00',
            endTime: '11:40',
            presentCount: 38,
            totalCount: 40,
            rate: 95
          }
        ]
      } catch (error) {
        console.error('加载统计失败:', error)
      }
    },
    
    async loadHistoryRecords() {
      try {
        // 模拟历史记录数据
        this.historyRecords = [
          {
            id: 1,
            courseName: 'Web前端开发',
            date: '2024-01-15',
            timeRange: '08:00-09:40',
            totalCount: 45,
            presentCount: 44,
            rate: 98
          },
          {
            id: 2,
            courseName: '数据库原理',
            date: '2024-01-14',
            timeRange: '10:00-11:40',
            totalCount: 40,
            presentCount: 38,
            rate: 95
          }
        ]
      } catch (error) {
        console.error('加载历史记录失败:', error)
      }
    },
    
    onCourseChange(e) {
      this.courseIndex = e.detail.value
    },
    
    onDurationChange(e) {
      this.durationIndex = e.detail.value
    },
    
    onDateChange(e) {
      this.filterDate = e.detail.value
      this.loadHistoryRecords()
    },
    
    viewDetail(record) {
      uni.navigateTo({
        url: `/pages/teacher/checkin-detail/checkin-detail?recordId=${record.id}`
      })
    },
    
    exportRecord(record) {
      uni.showToast({ title: '导出功能开发中', icon: 'none' })
    }
  }
}
</script>

<style scoped>
.checkin-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.header {
  background: white;
  padding: 40rpx 30rpx;
  border-bottom: 1rpx solid #eee;
}

.title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 24rpx;
  color: #666;
}

.tab-bar {
  display: flex;
  background: white;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 30rpx;
  font-size: 28rpx;
  color: #666;
  border-bottom: 4rpx solid transparent;
  transition: all 0.3s;
}

.tab-item.active {
  color: #667eea;
  border-bottom-color: #667eea;
  font-weight: bold;
}

.tab-content {
  padding: 30rpx;
}

.create-section {
  background: white;
  border-radius: 15rpx;
  padding: 30rpx;
}

.form-item {
  margin-bottom: 40rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: 500;
}

.picker-value {
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  text-align: center;
}

.qr-section {
  text-align: center;
  margin: 40rpx 0;
  padding: 30rpx;
  background: #f8f9fa;
  border-radius: 10rpx;
}

.section-title {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
}

.qrcode-canvas {
  width: 300rpx;
  height: 300rpx;
  margin: 0 auto 20rpx;
  background: #f0f0f0;
}

.session-code {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 10rpx;
  font-family: monospace;
}

.expire-time {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 30rpx;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
}

.btn {
  flex: 1;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 24rpx;
}

.primary {
  background: #667eea;
  color: white;
}

.secondary {
  background: #f5f5f5;
  color: #666;
}

.create-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 24rpx;
  font-size: 28rpx;
  width: 100%;
}

.create-btn:disabled {
  background: #ccc;
}

.stats-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
  margin-bottom: 40rpx;
}

.stat-card {
  background: white;
  border-radius: 10rpx;
  padding: 30rpx;
  text-align: center;
  border-left: 6rpx solid #667eea;
}

.stat-value {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.checkin-list {
  background: white;
  border-radius: 15rpx;
  padding: 30rpx;
}

.records {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #f8f9fa;
  border-radius: 10rpx;
}

.record-info {
  flex: 1;
}

.course-name {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.checkin-time, .student-count {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 5rpx;
}

.checkin-rate {
  font-size: 28rpx;
  font-weight: bold;
  color: #4caf50;
}

.record-item.detailed {
  flex-direction: column;
  align-items: stretch;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.record-date {
  font-size: 24rpx;
  color: #666;
}

.record-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15rpx;
  margin-bottom: 20rpx;
}

.detail-item {
  font-size: 24rpx;
  color: #666;
}

.record-actions {
  display: flex;
  gap: 15rpx;
}

.btn.small {
  padding: 16rpx 24rpx;
  font-size: 24rpx;
}

.empty-state {
  text-align: center;
  padding: 60rpx;
  color: #999;
}

.date-filter {
  background: white;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.filter-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}
</style>